package aimozg.joglfw.bones;

import aimozg.joglfw.JoglApplication;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;

/**
* Created by IntelliJ IDEA.
* User: aimozg
* Date: 03.01.11
* Time: 22:59
*/
public class Skeleton {
	private LinkedList<Bone> root_bones = new LinkedList<Bone>();
	private HashMap<String,Bone> all_bones = new HashMap<String,Bone>();
	private SkeletonAnimation animation;

	public Skeleton(Bone... rootBones) {
		for (Bone bone : rootBones) {
			this.root_bones.add(bone);
		}
		getAllBones();
	}

	public Skeleton(Collection<Bone> rootBones) {
		this.root_bones.addAll(rootBones);
		getAllBones();
	}

	public Skeleton(Skeleton other) {
		for (Bone bone : other.root_bones) {
			this.root_bones.add(bone.fullClone(null));
		}
		getAllBones();
		this.animation = other.animation;
	}

	private void getAllBones() {
		all_bones.clear();
		LinkedList<Bone> x_bones = new LinkedList<Bone>(root_bones);
		while (!x_bones.isEmpty()) {
			Bone bone = x_bones.removeFirst();
			x_bones.addAll(bone.children());
			all_bones.put(bone.name(),bone);
		}
	}

	public Skeleton setAnimation(SkeletonAnimation animation) {
		this.animation = animation;
		for (Bone bone : all_bones.values()) {
			bone.animation(animation.get(bone.name()));
		}
		return this;
	}

	public Skeleton remove(Bone bone) {
		root_bones.remove(bone);
		return this;
	}

	public void render(JoglApplication app, double progress) {
		for (Bone bone : root_bones) {
			bone.render(app, progress);
		}
	}

	public Bone bone(String name) {
		return all_bones.get(name);
	}

	@Override
	public Skeleton clone(){
		return new Skeleton(this);
	}
}
